import {Component} from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as todoActions from '../store/actions/todo.actions'
class Main extends Component {
  modifyTodo(ev, id) {
		this.props.modify_todo({id, isCompleted: ev.target.checked})
	}
  removeTodo(id) {
    if(window.confirm('确认删除？')){
      console.log('删除')
      this.props.remove_todo(id)
    }
	}
	saveEdit(data) {
		this.props.edit_todo({id: data.id, isEditing: false})
		this.props.rename_todo(data)
	}

  componentDidMount(){
    this.props.load_todo()
  }
  render() {
    console.log(this.props)
    return (
      <section className="main">
				{/* <!-- 批量更改任务状态 --> */}
				<input className="toggle-all" type="checkbox"/>
				<ul className="todo-list">
					{/* <!-- 
						当任务处于编辑状态时 添加editing类名
						当任务处于已完成状态时 添加completed类名
					--> */}
          {this.props.todos.map(item => {
            return(
              <li key={item.id} className={(item.isCompleted ? 'completed' : '') + ' ' + (item.isEditing ? 'editing' : '')}>
                {/* <!-- 任务展示视图 --> */}
                <div className="view">
                  <input className="toggle" type="checkbox" checked={item.isCompleted} onChange={(ev) => this.modifyTodo(ev,item.id)} /> {/*   */}
                  <label onDoubleClick={() => this.props.edit_todo({id: item.id, isEditing: true})}>{item.taskName}</label>
                  <button className="destroy" onClick={this.removeTodo.bind(this,item.id)}></button>
                </div>
                {/* <!-- 任务编辑视图 默认隐藏 --> */}
                <input className="edit" defaultValue={item.taskName}  onBlur={(ev) => this.saveEdit({id: item.id, taskName: ev.target.value})}/> {/* onBlur={(ev) => this.saveEdit({id: item.id, taskName: ev.target.value})} */}
              </li>
            )}
          )}
				</ul>
			</section>
    )
  }
}
const mapStateToProps = (state) => ({
  todos: filterTodos(state.todoReducer.todos,state.todoReducer.filter)
})

const mapDispatchToProps = (dispatch) => ({
  ...bindActionCreators(todoActions, dispatch)
})

function filterTodos(todos, filter) {
  switch (filter){
    case 'all':
      return todos
    case 'active':
      return todos.filter(todo => !todo.isCompleted)
    case 'completed':
      return todos.filter(todo => todo.isCompleted)
    default:
      return todos
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)